package com.lsj.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.lsj.common.utils.HttpUtils;
import com.lsj.gulimall.member.dao.MemberLevelDao;
import com.lsj.gulimall.member.entity.MemberLevelEntity;
import com.lsj.gulimall.member.execption.PhoneExistException;
import com.lsj.gulimall.member.execption.UserNameExistException;
import com.lsj.gulimall.member.vo.GiteeSocialUser;
import com.lsj.gulimall.member.vo.GiteeUser;
import com.lsj.gulimall.member.vo.MemberRegisterVo;
import com.lsj.gulimall.member.vo.UserLoginVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsj.common.utils.PageUtils;
import com.lsj.common.utils.Query;

import com.lsj.gulimall.member.dao.MemberDao;
import com.lsj.gulimall.member.entity.MemberEntity;
import com.lsj.gulimall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    MemberLevelDao memberLevelDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        // 设置默认等级
         MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
         memberEntity.setLevelId(memberLevelEntity.getId());

         // 检查用户名和密码是否唯一，为了让controller能感知异常，使用异常抛出机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        // 密码要进行加密储存
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        // 其他的默认信息

        // 保存
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUserNameUnique(String userName) throws PhoneExistException {
        Integer username = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            new PhoneExistException();
        }
    }


    @Override
    public void checkPhoneUnique(String phone) throws UserNameExistException {
        Integer phoneNum = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (phoneNum > 0 ) {
            new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        List<MemberEntity> members = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginAccount()));
        if (members != null && members.size() > 0) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(vo.getPassword(), members.get(0).getPassword());
            if (matches) {
                //登录成功
                return members.get(0);
            }
        }
        // 登录失败
        return null;
    }

    @Override
    public MemberEntity socialLogin(GiteeSocialUser socialUser) throws Exception {
        MemberEntity memberEntity = null;
        if (socialUser != null) {
            // 获取第三方的用户信息
            String access_token = socialUser.getAccess_token();
            Map<String,String> map = new HashMap<>();
            map.put("access_token",access_token);
            HttpResponse httpResponse = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String jsonString = EntityUtils.toString(httpResponse.getEntity());
                GiteeUser giteeUser = JSON.parseObject(jsonString, GiteeUser.class);
                // 查看数据库是否已存在该用户
                // 存在
                List<MemberEntity> userList = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("gitee_id", giteeUser.getId()));
                if (userList != null && userList.size() > 0) {
                    memberEntity = userList.get(0);
                } else {
                    // 不存在,新增用户
                    MemberEntity entity = new MemberEntity();
                    entity.setUsername(giteeUser.getLogin());
                    entity.setNickname(giteeUser.getName());
                    entity.setHeader(giteeUser.getAvatar_url());
                    entity.setGitee_id(giteeUser.getId());
                    entity.setCreateTime(new Date());
                    MemberLevelEntity defaultLevel = memberLevelDao.getDefaultLevel();
                    entity.setLevelId(defaultLevel.getId());
                    entity.setEmail(giteeUser.getEmail());
                    baseMapper.insert(entity);
                    memberEntity = entity;
                }
            }

        }
        return memberEntity;
    }


}